$(function() {
  $.initPage(adminRoleList.load.start);
});

var adminRoleList = new BaseFrame();

adminRoleList.addBlock('search', 'list', 'pagination', 'detail');

//load module
adminRoleList.load.addStart(function() {
  var params = adminRoleList.data.search.params;
  params.isSuperUser = false;
  _user.isSuperUser = false;
  params.userFormIds = !$.isEmpty(_user.others) && !$.isEmpty(_user.others.formIds) ? _user.others.formIds : null;
  $.get(_apiPath + '/Apps/formList', params)
  .then(function(result){
    //verify if this account is superuser? it is super user when has all form privileges
    if (!$.isEmpty(result)){
      var formIds = [];
      result.forEach(function(item){
        formIds.push(item.id.toString());
      });
      var diffArray = _.difference(formIds, params.userFormIds);
      if (diffArray.length == 0){ // is super user
        params.isSuperUser = true;
        _user.isSuperUser = true;
      }
    }
    return $.get(_apiPath + '/Admins/Role/Page', params);
  }).then(function(data) {
      _data = $.extend({}, data);      
      return $.pageStart(_adminSettings);
    })
    .then(function() {
      adminRoleList.load.runTask();
      adminRoleList.event.runTask();
      adminRoleList.load.list.create(_data.roleList);
    });
});

adminRoleList.load.addBind('createTitle', function() {
  var currentPage = $.getCurrentPage(_adminSettings.pageList);
  $('title').text(currentPage.title);
});

adminRoleList.load.addBind('createNav', function() {
  $('#logout').on('click', $.logoff);
  var navList = $.getUserAuthorityList(_user.roleList, _adminSettings.authorityList, _adminSettings.pageList);
  $('#block-nav').createNavList(navList).removeClass('dn');
});

adminRoleList.load.list.addBind('createListTitle', function() {
  var currentPage = $.getCurrentPage(_adminSettings.pageList);
  $('#block-list .panel-title').text($.toString(currentPage.title));
});

adminRoleList.load.list.addEvent('create', function(dataList) {
  if (dataList.length == 0) {
    $('#block-alert').text(_enumMessage.noSearchResult);
    $('#list-list tbody').addClass('dn');
    $('#block-alert').removeClass('dn');
    $('#block-pagination').addClass('dn');
  } else {
    var template = $('#template-list-detail').html();
    $('#list-list tbody').empty().createListTemplate(template, dataList);
    adminRoleList.load.pagination.create(_data.pageTotal);
    $('#list-list tbody').removeClass('dn');
    $('#block-alert').addClass('dn');
  }
  $('#block-list').removeClass('dn');
  var params = adminRoleList.data.search.params;
  if ($.isEmpty(params.userFormIds)) $('.btn[create]').addClass('dn');
});

adminRoleList.load.list.addEvent('update', function(pageNumber) {
  var params = adminRoleList.save.search.params();
  params.pageNumber = pageNumber || params.pageNumber;
  $.get(_apiPath + '/Admins/Role', params)
    .then(function(data) {
      if (data.pageId != adminRoleList.data.search.params.pageId) return false;
      _data.roleList = data.roleList;
      _data.formList = data.formList;
      _data.pageTotal = data.pageTotal;
      adminRoleList.load.list.create(_data.roleList);
    });
});

adminRoleList.load.pagination.addEvent('create', function(pageTotal, pageNumber, pageSize) {
  if ($.isEmpty(pageTotal) || pageTotal < 1) return;
  pageNumber = pageNumber || adminRoleList.data.search.params.pageNumber;
  pageSize = pageSize || adminRoleList.data.search.params.pageSize;
  $('#block-pagination').empty().createPagination({
    pageNumber: pageNumber,
    pageTotal: pageTotal,
  }).removeClass('dn');
});

adminRoleList.load.detail.addEvent('create', function(detailData) {
  var domStorage = $('#form-detail');
  domStorage.data('detail', $.extend({}, detailData));
  $('#field-detail-name').empty().createString(domStorage, 'detail.name', {
    required: true,
  });
  $('#field-detail-comment').empty().createString(domStorage, 'detail.comment', {
    required: true,
  });
  $('#field-detail-isApprover').empty().createSelect(domStorage, 'detail.isApprover', $.createSelect(), {
    required: true,
  });
  $('#field-detail-isDefault').empty().createSelect(domStorage, 'detail.isDefault', $.createSelect(), {
    required: true,
  });
  $('#field-detail-ta').empty().createString(domStorage, 'detail.type');
  domStorage.data('detail').formIdList = [];
  var userFormList = !$.isEmpty(_user.others) && !$.isEmpty(_user.others.formIds) ? _user.others.formIds : null;
  if (!$.isEmpty(userFormList)){
    var formList = [];
    userFormList.forEach(function(item){
      formList.push({
        id: item,
        name:_.find(_data.formList, {'id': parseInt(item)}).formChineseName
      });
    });
    if (!$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)){
      detailData.others.formIds.forEach(function(item){
        domStorage.data('detail').formIdList.push(item);
      });
    }
    var options = {required: true};
    if (_user.isSuperUser)
      options = {required: true, allSelected:true}
    $('#field-detail-form').empty().createCheckbox(domStorage, 'detail.formIdList', $.getKeyValueListByIdName(formList), options);
  }
});

adminRoleList.load.addEvent('roleList', function(roleList) {
  var roleNameList = '';
  for (var i = 0; i < roleList.length; i++)
    roleNameList += ',' + roleList[i].name;
  return roleNameList.replace(',', '');
});

adminRoleList.load.addEvent('formList', function(others) {
  var formNameList = '';
  if (!$.isEmpty(others) && !$.isEmpty(others.formIds)){
    for (var i = 0; i < others.formIds.length; i++) {
      _data.formList.forEach(function(item){
        if (others.formIds[i] == item.id){
          if (!formNameList.includes(item.formChineseName)) {
            formNameList += ',' + item.formChineseName;
          }
        }
      });
    }
  }
  return formNameList.replace(',', ' ');
});

adminRoleList.load.addEvent('deleted', function(deleted) {
  if ($.isZero(deleted)) return '已删除';
  return '未删除';
});

//event module
adminRoleList.event.list.addBind('operation', function() {
  $('#list-list').on('click', '.btn[create]', function() {
    var detailData = $.extend({}, adminRoleList.data.detail.params);
    adminRoleList.load.detail.create(detailData);
    $('#modal-detail').modal('show');
  });

  $('#list-list').on('click', '.btn[update]', function() {
    var detailData = $.extend({}, adminRoleList.data.detail.params, $(this).parents('tr[data]').data('data'));
    adminRoleList.load.detail.create(detailData);
    $('#modal-detail').modal('show');
  });

  $('#list-list').on('click', '.btn[delete]', function() {
    var detailData = $.extend({}, $(this).parents('tr[data]').data('data'));
    $.confirm(adminRoleList.message.list.deleteDetail, function() {
      adminRoleList.form.deleteDetail(detailData);
    });
  });
});

adminRoleList.event.pagination.addBind('operation', function() {
  $('#block-pagination').on('changeCallback', function(event, currentPage, targetPage) {
    adminRoleList.load.list.update(targetPage)
  });
});

adminRoleList.load.search.addBind('create', function() {
  // if (eLancoApprovalList.verify.isSubmitModel()) return;
  var domStorage = $('#form-search');
  $('#field-search-type').createSelect(domStorage, 'search.userFormIds', $.getKeyValueList('id', 'formChineseName', _data.formList), {
    verify: false,
    firstOption: _allSelect,
});
  $('#field-search-Keywords').createString(domStorage, 'search.name', $.getKeyValueList('id', 'formChineseName', _data.formList), {
      verify: false,
  });

  $('#block-search .search-item[formId]').hide();
  $('#block-search').removeClass('dn');
});

//save module
adminRoleList.save.search.addEvent('params', function(pageNumber) {
  var data = $('#form-search').data();
  pageNumber = pageNumber || adminRoleList.data.search.params.pageNumber;
  adminRoleList.data.search.params.pageId++;
  adminRoleList.data.search.params.pageNumber = pageNumber;
  adminRoleList.data.search.params.name = data.search.name;
  adminRoleList.data.search.params.userFormIds = _user.others.formIds; 
  adminRoleList.data.search.params.isSuperUser = data.search.name ? 'false' : 'true' ;
  return adminRoleList.data.search.params;
});

adminRoleList.event.search.addBind('operation', function() {
  $('#block-search').on('click', '#search-btn', function() {
      adminRoleList.load.list.update(1);
      return false;
  });
});

adminRoleList.event.detail.addBind('operation', function() {
  $('#modal-detail').on('submit', '#form-detail', function(event) {
    var thisDom = $(this);
    var params = thisDom.data('detail');
    var others = _.isEmpty(params.others) ? {} : params.others;
    _.assign(others, {'formIds': params.formIdList});
    params.others = others;
    thisDom.find('[form]').findFormUnit().verifyClean();
    if (!adminRoleList.verify.detail.params(params)) return false;
    adminRoleList.form.saveDetail(params);
    return false;
  });
});

//form module
adminRoleList.form.addEvent('saveDetail', function(params) {
  var others = _.isEmpty(params.others) ? {} : params.others;
  var detailData = _.find(_data.roleList, {'id': params.id});
  if (!$.isEmpty(detailData) && !$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)) params.formIdList = detailData.others.formIds;  
  _.assign(others, {'formIds': params.formIdList});
  params.others = others;
  $.post(_apiPath + '/Admins/Role/' + params.id + '/Save', params)
    .done(function(result) {
      $('#modal-detail').modal('hide');
      $.alert(_enumMessage.saveSuccess, adminRoleList.load.list.update);
    });
});

adminRoleList.form.addEvent('deleteDetail', function(params) {
  var detailData = _.find(_data.roleList, {'id': params.id});
  var deleteDirect = true;
  if (!$.isEmpty(detailData.others) && !$.isEmpty(detailData.others.formIds)){
    var userFormList = !$.isEmpty(_user.others) && !$.isEmpty(_user.others.formIds) ? _user.others.formIds : null;
    if (!$.isEmpty(userFormList)){
      var intersectionArray = _.intersection(detailData.others.formIds, userFormList);
      var differenceArray = _.difference(detailData.others.formIds, intersectionArray);
      if (differenceArray.length > 0){
        var others = _.isEmpty(params.others) ? {} : params.others;
        _.assign(others, {'formIds': differenceArray});
        params.others = others;
        deleteDirect = false;
      }
    }
  }
  console.log(deleteDirect);
  if (deleteDirect){
    $.delete(_apiPath + '/Admins/Role/' + params.id, params)
    .then(function(result) {
      console.log(result);
      $.alert(_enumMessage.deleteSuccess, adminRoleList.load.list.update);
    });
  } else {
    $.post(_apiPath + '/Admins/Role/' + params.id + '/Save', params)
    .done(function(result) {
      $('#modal-detail').modal('hide');
      $.alert(_enumMessage.deleteSuccess, adminRoleList.load.list.update);
    });
  }
});

//verify module
adminRoleList.verify.detail.addEvent('params', function(params) {
  var judge = true;
  if ($.isEmpty(params.name)) {
    judge = false;
    $('#field-detail-name').verifyErrorAndHelp(adminRoleList.message.detail.roleNameRequired);
  }
  if ($.isEmpty(params.comment)) {
    judge = false;
    $('#field-detail-comment').verifyErrorAndHelp(adminRoleList.message.detail.roleDescRequired);
  }
  if ($.isEmpty(params.isApprover)) {
    judge = false;
    $('#field-detail-isApprover').verifyErrorAndHelp(adminRoleList.message.detail.approverRequired);
  }
  if ($.isEmpty(params.isDefault)) {
    judge = false;
    $('#field-detail-isDefault').verifyErrorAndHelp(adminRoleList.message.detail.defaultRequired);
  }
  if ($.isEmpty(params.formIdList)){
    judge = false;
    $('#field-detail-form').verifyErrorAndHelp(adminRoleList.message.detail.formRequired);
  }

  return judge;
});

//message module
adminRoleList.message.list.addConfig('deleteDetail', '是否删除detail');

adminRoleList.message.detail.addConfig('roleNameRequired', '角色名称必填');
adminRoleList.message.detail.addConfig('roleDescRequired', '角色描述必填');
adminRoleList.message.detail.addConfig('approverRequired', '是否approver必填');
adminRoleList.message.detail.addConfig('defaultRequired', '是否default必填');
adminRoleList.message.detail.addConfig('formRequired', '所属表单必填');

// //data module
adminRoleList.data.search.addConfig('params', {
  pageId: 0,
  pageNumber: 1,
  pageSize: 8,
});

adminRoleList.data.detail.addConfig('params', {
  id: 0,
  name: '',
  principal_id: '',
  parent_id: '',
  comment: '',
  description: '',
  others: {}
});